package top.zy.page.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.zy.page.client.BrandClient;
import top.zy.page.client.CategoryClient;
import top.zy.page.client.GoodsClient;
import top.zy.page.client.SpecClient;
import top.zy.service.zymallgoodsinterface.entity.*;
import top.zy.service.zymallgoodsinterface.vo.GoodsVo;
import top.zy.service.zymallgoodsinterface.vo.SpecGroupVo;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 20:54 2019/7/7
 */
@Service
@Slf4j
public class PageServiceImpl implements PageService {


    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecClient specClient;

    @Autowired
    private TemplateEngine templateEngine;

    public Map<String, Object> loadData(Long spuId) {
        Map<String, Object> data = new HashMap<>();
        GoodsVo spu = goodsClient.querySpuBySpuId(spuId);
        List<Sku> skus = spu.getSkus();
        SpuDetail detail = spu.getSpuDetail();
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        List<Category> categories = categoryClient.queryCategoryListByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        List<SpecGroupVo> specs = specClient.querySpecGroupAndParamByCid(spu.getCid3());
        data.put("skus", skus);
        data.put("brand", brand);
        data.put("categories", categories);
        data.put("spu", spu);
        data.put("detail", detail);
        data.put("specs", specs);
        return data;
    }

    public void createHtml(Long spuId) {
        //上下文拿数据
        Context context = new Context();
        context.setVariables(loadData(spuId));
        //输出流
        File dest = new File("F:/nginx-1.12.1/html/item", spuId + ".html");
        try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
           //生成html
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("{静态页服务}生成静态页异常", e);
        }
    }

    public void deleteHtml(Long spuId) {
        try{
            File file = new File("F:/nginx-1.12.1/html/item", spuId + ".html");
            file.delete();
        } catch (Exception e) {
            log.error("{静态页服务}删除spuId:{},静态页异常",spuId, e);
        }
    }
}
